<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

// ------------------------------------------------------------------------

/**
 * CSV Helpers
 * Inspiration from PHP Cookbook by David Sklar and Adam Trachtenberg
 * 
 * @author		Jérôme Jaglale
 * @link		http://maestric.com/en/doc/php/codeigniter_csv
 */

// ------------------------------------------------------------------------

/**
 * Array to CSV
 *
 * download == "" -> return CSV string
 * download == "toto.csv" -> download file toto.csv
 */
if ( ! function_exists('array_to_csv'))
{
	function array_to_csv($array, $download = "")
	{
		if ($download != "")
		{	
			header('Content-Type: application/csv');
			header('Content-Disposition: attachement; filename="' . $download . '"');
		}		

		ob_start();
		$f = fopen('php://output', 'w') or show_error("Can't open php://output");
		$n = 0;		
		foreach ($array as $line)
		{
		  /*---add---*/
          if($n == 0)
          {
            array_unshift($line, 'No');
          }else{
            array_unshift($line, $n);
          }
          /*--end---*/
          
			$n++;
			if ( ! fputcsv($f, $line))
			{
				show_error("Can't write line $n: $line");
			}
		}
		fclose($f) or show_error("Can't close php://output");
		$str = ob_get_contents();
		ob_end_clean();

		if ($download == "")
		{
			return $str;	
		}
		else
		{	
			echo $str;
		}		
	}
}

// ------------------------------------------------------------------------

/**
 * Query to CSV
 *
 * download == "" -> return CSV string
 * download == "toto.csv" -> download file toto.csv
 */
if ( ! function_exists('query_to_csv'))
{
	function query_to_csv($query, $headers = TRUE, $download = "")
	{
		if ( ! is_object($query) OR ! method_exists($query, 'list_fields'))
		{
			show_error('invalid query');
		}
		
		$array = array();
		
		if ($headers)
		{
			$line = array();
			foreach ($query->list_fields() as $name)
			{
				$line[] = $name;
			}
			$array[] = $line;
		}
		
		foreach ($query->result_array() as $row)
		{
			$line = array();
			foreach ($row as $item)
			{
                /*--modified--*/
                if (startsWith($item, 00) || startsWith($item, '00')){
                    $line[] = "'".$item;
                }
                elseif(startsWith($item, 'refend'))
                {
                    $item = substr($item, 6);
                    $refs = explode(",", $item);
                    if(count($refs) && count($refs) == 2)
                    {
                        $line[] = "'".generateRefFormat(trim($refs[0]), trim($refs[1]));
                    }else{
                        $line[] = 'N/A';
                    }
                }
                else{
                    $line[] = $item;
                }
                /**/
			}
			$array[] = $line;
		}

		echo array_to_csv($array, $download);
	}
    
   	function report_printing_csv($query, $headers = TRUE, $download = "")
	{
		/*if ( ! is_object($query) OR ! method_exists($query, 'list_fields'))
		{
			show_error('invalid query');
		}*/
		
		$array = array();
        
        $fields = array();
        $fields[] = "Item";
        $fields[] = "Buy Unit";
        $fields[] = "Amount";
        $fields[] = "Used Unit";
        $fields[] = "Amount";
        $fields[] = "Broken";
		$fields[] = "Amount";
        $fields[] = "Balance";
        $fields[] = "Amount";
        
        $array[] = $fields;
        
        $buy = 0;
        $amtbuy = 0;
        $used = 0;
        $amtused = 0;
        $broken = 0; 
        $amtbroken = 0;$stockin = 0;$amtstock = 0;
		foreach ($query as $item)
		{
            $line = array();
            $line[] = $item->item;
            $line[] = $item->buy;
            $line[] = $item->totalbuy;
            $line[] = !empty($item->unitused) ? $item->unitused : '0';
            $line[] = !empty($item->totalused) ? $item->totalused : '0';
            $line[] = !empty($item->unitbroken) ? $item->unitbroken : '0';
            $line[] = !empty($item->totalbroken) ? $item->totalbroken : '0';
            $line[] = $item->balance;
            $line[] = $item->amount;
            $array[] = $line;
            
            $buy += $item->buy;
            $amtbuy += $item->totalbuy;
            $used += $item->unitused;
            $amtused += $item->totalused;
            $broken += $item->unitbroken;
            $amtbroken += $item->totalbroken;
            $stockin += $item->balance;
            $amtstock += $item->amount;
		}
        $alls = array();
        $alls[] = '';
        $alls[] = '';
        $alls[] = '';
        $alls[] = '';
        $alls[] = '';
        $alls[] = '';
        $alls[] = '';
        $alls[] = '';
        $alls[] = '';
        $alls[] = '';
        $array[] = $alls;
        
        $alls = array();
        $alls[] = '';
        $alls[] = '';
        $alls[] = '';
        $alls[] = '';
        $alls[] = '';
        $alls[] = '';
        $alls[] = '';
        $alls[] = '';
        $alls[] = '';
        $alls[] = '';
        $array[] = $alls;
        
        $alls = array();
        $alls[] = 'Total';
        $alls[] = $buy;
        $alls[] = $amtbuy;
        $alls[] = $used;
        $alls[] = $amtused;
        $alls[] = $broken;
        $alls[] = $amtbroken;
        $alls[] = $stockin;
        $alls[] = $amtstock;
        
        $array[] = $alls;
		echo array_to_csv($array, $download);
	}
    
    function generateRefFormat($startRef, $endRef)
    {
        if(empty($startRef))
        {
            return '';
        }
        $ref = '';
        if($endRef > 0)
        {
            $endRef = $endRef - 1;
        }
        if(strlen($startRef) > strlen($endRef))
        {
            for($i = 0; $i < (strlen($startRef) - strlen($endRef)); $i++)
            {
                $ref .= '0';
            }
        }
        return $ref.''.$endRef;
    } 
    
    function startsWith($haystack, $needle)
    {
        return $needle === "" || strpos($haystack, $needle) === 0;
    }
    function endsWith($haystack, $needle)
    {
        return $needle === "" || substr($haystack, -strlen($needle)) === $needle;
    }
}

/* End of file csv_helper.php */
/* Location: ./system/helpers/csv_helper.php */